﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;

using Fuse8.DomainFramework.Common;
using Fuse8.DomainFramework.Configuration;

namespace Fuse8.DomainFramework.DataAccess
{
    /// <summary>
    /// 
    /// </summary>
    internal static class SqlConnectionFactoryWrapper
    {
        private static object _syncRoot = new object();

        /// <summary>
        /// 
        /// </summary>
        public static readonly string CurrentSqlConnectionKey = "CurrentSqlConnection";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="connectionString"></param>
        /// <param name="withTransaction"></param>
        /// <returns></returns>
        public static SqlConnection GetOrCreateConnection(HttpContextBase httpContext, string connectionString, bool withTransaction)
        {
            Guard.ArgumentNotNull(httpContext, "httpContext");
            Guard.ArgumentNotEmpty(connectionString, "connectionString");

            SqlConnection result = null;

            lock (_syncRoot)
            {
                if (!withTransaction)
                {
                    if (DataRepositoryConfiguration.AlwaysCreateSqlConnection)
                    {
                        result = new SqlConnection(connectionString);
                    }
                    else
                    {
                        result = httpContext.Items[CurrentSqlConnectionKey] as SqlConnection;

                        if (result == null)
                        {
                            result = new SqlConnection(connectionString);

                            httpContext.Items[CurrentSqlConnectionKey] = result;
                        }
                    }
                }
                else
                {
                    result = new SqlConnection(connectionString);
                }

                if (result.State != ConnectionState.Open)
                {
                    result.Open();
                }
            }

            return result;
        }
    }
}
